// packageAPI/pages/device/wifi/wifi.js
Page({
  data: {
    title: '',
    zh: '',
    webUrl: '',
    schema: [
      {
        label: 'Wi-Fi名称 (SSID)',
        prop: 'SSID',
        type: 'text',
        placeholder: '请输入要连接的Wi-Fi名称'
      },
      {
        label: 'Wi-Fi密码',
        prop: 'password',
        type: 'text',
        placeholder: '请输入Wi-Fi密码（可选）'
      }
    ],
    formData: {},
    result: '',
    apiName: "",
    // Wi-Fi相关数据
    listenStatus: {
      wifiConnected: false,
      getWifiList: false
    },
    // 存储监听器函数引用
    listeners: {
      wifiConnected: null,
      getWifiList: null
    }
  },

  onLoad: function (options) {
    console.log('WiFi页面加载');
    console.log('路由传递的参数:', options);
    
    // 处理路由参数
    if (options) {
      const routeData = {
        zh: options.zh,            
        title: options.title,       
        remark: options.remark,
        webUrl: options.webUrl    
      };
      
      this.setData({  
        title: routeData.title,       
        zh: routeData.zh,
        webUrl: routeData.webUrl,
        apiName: routeData.zh,
        result: `页面加载完成 - ${routeData.title}`
      });
    } else {
      this.setData({
        title: 'Wi-Fi API',                           
        zh: 'Wi-Fi API',
        webUrl: '',
        apiName: 'Wi-Fi API',
        result: '页面加载完成 - 使用默认配置'
      });
    }
  },

  // API处理函数
  handleApiCall: function (e) {
    const apiName = e.currentTarget.dataset.apiname;

    this.setData({
      apiName: apiName
    });

    switch (apiName) {
      case 'wx.stopWifi':
        this.stopWifiFunc();
        break;
      case 'wx.startWifi':
        this.startWifiFunc();
        break;
      case 'wx.onWifiConnected':
        this.toggleWifiConnectedListener();
        break;
      case 'wx.onGetWifiList':
        this.toggleWifiListListener();
        break;
      case 'wx.offWifiConnected':
        this.offWifiConnectedFunc();
        break;
      case 'wx.offGetWifiList':
        this.offGetWifiListFunc();
        break;
      case 'wx.getWifiList':
        this.getWifiListFunc();
        break;
      case 'wx.getConnectedWifi':
        this.getConnectedWifiFunc();
        break;
      case 'wx.connectWifi':
        this.connectWifiFunc();
        break;
      default:
        this.showResult(`未知的API: ${apiName}`);
    }
  },

  // 表单数据变化回调
  getFormData(e) {
    const { formData } = e.detail;
    this.setData({
      formData: formData,
      result: JSON.stringify(formData)
    });
  },
  
  // 显示API调用结果
  showResult(result) {
    this.setData({
      result: result
    });
  },

  // 停止Wi-Fi模块
  stopWifiFunc() {
    wx.stopWifi({
      success: (res) => {
        console.log('停止Wi-Fi模块成功:', res);
        this.showResult(res);
        this.setData({
          'listenStatus.wifiConnected': false,
          'listenStatus.getWifiList': false
        });
      },
      fail: (err) => {
        this.showResult(err);
      }
    });
  },

  // 启动Wi-Fi模块
  startWifiFunc() {
    wx.startWifi({
      success: (res) => {
        console.log('启动Wi-Fi模块成功:', res);
        this.showResult(res);
      },
      fail: (err) => {
        this.showResult(err);
      }
    });
  },

  // 切换Wi-Fi连接监听器
  toggleWifiConnectedListener() {
    if (this.data.listenStatus.wifiConnected) {
      // 使用相同的监听器函数引用进行注销
      wx.offWifiConnected(this.data.listeners.wifiConnected);
      console.log(wx.offWifiConnected(this.data.listeners.wifiConnected),99999)
      this.setData({
        'listenStatus.wifiConnected': false,
        'listeners.wifiConnected': null,
        result: '已停止监听Wi-Fi连接事件'
      });
    } else {
      // 创建监听器函数引用
      const wifiConnectedListener = function(res) {
        console.log('Wi-Fi连接成功:', res);
        this.showResult(`Wi-Fi连接成功:\nSSID: ${res.wifi.SSID}\nBSSID: ${res.wifi.BSSID}\nsignalStrength: ${res.wifi.signalStrength}`);
      }.bind(this);
      
      wx.onWifiConnected(wifiConnectedListener);
      this.setData({
        'listenStatus.wifiConnected': true,
        'listeners.wifiConnected': wifiConnectedListener,
        result: '已开始监听Wi-Fi连接事件'
      });
    }
  },

  // 切换Wi-Fi列表监听器
  toggleWifiListListener() {
    if (this.data.listenStatus.getWifiList) {
      // 使用相同的监听器函数引用进行注销
      wx.offGetWifiList(this.data.listeners.getWifiList);

      this.setData({
        'listenStatus.getWifiList': false,
        'listeners.getWifiList': null,
        result: '已停止监听Wi-Fi列表事件'
      });
    } else {
      // 创建监听器函数引用
      const getWifiListListener = function(res) {
        console.log('获取Wi-Fi列表成功:', res);
        const wifiList = res.wifiList || [];
        this.showResult(`获取到${wifiList.length}个Wi-Fi:\n${wifiList.map(wifi => `• ${wifi.SSID} (${wifi.signalStrength}%)`).join('\n')}`);
      }.bind(this);
      
      wx.onGetWifiList(getWifiListListener);
      this.setData({
        'listenStatus.getWifiList': true,
        'listeners.getWifiList': getWifiListListener,
        result: '已开始监听Wi-Fi列表事件'
      });
    }
  },

  // 移除Wi-Fi连接事件监听
  offWifiConnectedFunc() {
    // 使用相同的监听器函数引用进行注销
    wx.offWifiConnected(this.data.listeners.wifiConnected);
    this.setData({
      'listenStatus.wifiConnected': false,
      'listeners.wifiConnected': null,
      result: '已移除Wi-Fi连接事件监听器'
    });
  },

  // 移除Wi-Fi列表事件监听
  offGetWifiListFunc() {
    // 使用相同的监听器函数引用进行注销
    wx.offGetWifiList(this.data.listeners.getWifiList);
    this.setData({
      'listenStatus.getWifiList': false,
      'listeners.getWifiList': null,
      result: '已移除Wi-Fi列表事件监听器'
    });
  },

  // 获取Wi-Fi列表
  getWifiListFunc() {
    wx.getWifiList({
      success: (res) => {
      
        this.showResult(res);
      },
      fail: (err) => {
       
        this.showResult(err);
      }
    });
  },

  // 获取已连接的Wi-Fi信息
  getConnectedWifiFunc() {
    wx.getConnectedWifi({
      success: (res) => {
        this.showResult(res);
      },
      fail: (err) => {
        this.showResult(err);
      }
    });
  },

  // 连接指定Wi-Fi
  connectWifiFunc() {
    // 检查是否有表单数据
    if (!this.data.formData || !this.data.formData.SSID) {
      this.showResult('请在上方表单中输入要连接的Wi-Fi信息：\nSSID: WiFi名称\npassword: WiFi密码');
      return;
    }

    const wifiConfig = {
      SSID: this.data.formData.SSID,
      password: this.data.formData.password || ''
    };

    // 验证必要参数
    if (!wifiConfig.SSID) {
      this.showResult('错误：请输入Wi-Fi名称 (SSID)');
      return;
    }

    wx.connectWifi({
      SSID: wifiConfig.SSID,
      password: wifiConfig.password,
      success: (res) => {
        this.showResult(res);
      },
      fail: (err) => {
        this.showResult(err);
      }
    });
  },
})